package com.ry.demo.register.server;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 注册表
 */
public class Registry {

    /**
     * 注册表是一个单例
     */
    private static Registry instance = new Registry();

    private Registry() {
        // 构造器私有
    }


    /**
     * 保存了所有注册过的服务实例信息
     * [
     *  服务名 : [服务实 例ID: 服务实例]
     * ]
     *
     */
    private Map<String, Map<String,ServiceInstance>> registry = new HashMap<>();


    /**
     * 服务注册
     * @param serviceInstance 服务实例
     */
    public void addInstance(ServiceInstance serviceInstance){

        Map<String, ServiceInstance> serviceInstanceMap = registry.get(serviceInstance.getServiceName());

        if (serviceInstanceMap == null){
            serviceInstanceMap = new HashMap<>();
            registry.put(serviceInstance.getServiceName(),serviceInstanceMap);
        }

        serviceInstanceMap.put(serviceInstance.getServiceInstanceId(),serviceInstance);

        System.out.println("服务实例【" + serviceInstance + "】，完成注册......");
        System.out.println("注册表：" + registry);
    }


    /**
     * 获取整个注册表
     * @return
     */
    public Map<String, Map<String, ServiceInstance>> getRegistry() {
        return registry;
    }

    /**
     * 获取服务实例
     * @param serviceName       服务名
     * @param serviceInstanceId 服务实例ID
     */
    public ServiceInstance getServiceInstance(String serviceName,String serviceInstanceId){

        Map<String, ServiceInstance> serviceInstanceMap = registry.get(serviceName);
        if (serviceInstanceMap == null){
            return null;
        }
        return serviceInstanceMap.get(serviceInstanceId);
    }

    /**
     * 摘除故障服务实例
     */
    public void removeInstance(String serviceName,String serviceInstanceId){

        Map<String, ServiceInstance> serviceInstanceMap = registry.get(serviceName);
        if (serviceInstanceMap != null){
            serviceInstanceMap.remove(serviceInstanceId);
        }
    }


    public static Registry getInstance() {
        return instance;
    }
}
